package com.pzh.vue.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzh.vue.common.Constants;
import com.pzh.vue.common.Result;
import com.pzh.vue.exception.ServiceException;
import com.pzh.vue.mapper.StudentFileMapper;
import com.pzh.vue.pojo.SysFile;
import com.pzh.vue.pojo.SysStudentFile;
import com.pzh.vue.pojo.SysUser;
import com.pzh.vue.service.FileService;
import com.pzh.vue.service.SysUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${file.path}")
    private String filepath;
    @Value("${server.ip}")
    private String serverIp;
    @Value("${file.student}")
    private String studentPath;
    @Autowired
    private FileService fileService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private StudentFileMapper studentFileMapper;
    /**
     * 文件上传操作
     * @param file
     * @return
     * @throws IOException
     */
   @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String url="";
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件大小
        long size = file.getSize();
        //类型
        String type = FileUtil.extName(originalFilename);
        //创建父级目录
        File uploadParentFile=new File(filepath);
        if (!(uploadParentFile.exists())){
             uploadParentFile.mkdir();
        }
        //防止重名 定义文件标识码
        String uuid= IdUtil.simpleUUID();
        File uploadFile=new File(filepath+"/"+uuid+'.'+type);
        //获取文件MD5 校验是否重复文件
        String md5= SecureUtil.md5(file.getInputStream());
        //根据MD5去数据库校验是否存在
        SysFile serviceMd5 = fileService.findMd5(md5);
        //判断文件是否存在
        if (serviceMd5==null){
            //把获取file存入系统磁盘
           file.transferTo(uploadFile);
           url= "http://"+serverIp+":8081/file/"+uuid+'.'+type;
           SysFile saveFile=new SysFile();
           saveFile.setName(originalFilename);
           saveFile.setType(type);
           saveFile.setSize(size/1024);
           saveFile.setUrl(url);
           saveFile.setMd5(md5);
           fileService.saveFile(saveFile);
       }
        else {
            QueryWrapper<SysFile> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("md5", md5);
            SysFile one = fileService.getOne(queryWrapper);
            url=one.getUrl();
        }

       return url;
    }
    //学生文件上传
    @PostMapping("/studentUpload")
    public String upload(@RequestParam MultipartFile file, @RequestParam String username) throws IOException {
       //如果没有文件
       if (file==null){
           System.out.println("i am do");
           return "NoFile";
       }
        String originalFilename = file.getOriginalFilename();
        //查询学生url
        String fileUrl = sysUserService.selectFile(username);
        //如果已有学生文件
        if (fileUrl!=null){
            String name = studentFileMapper.findNameByURL(fileUrl);
            System.out.println(studentPath+"/"+name);
            File uploadFile=new File(studentPath+"/"+name);
            uploadFile.delete();//删除查询到的学生文件
            //删除数据库记录
            studentFileMapper.deleteByUrl(fileUrl);
        }
        String url="";
        //获取文件名

        //获取文件大小
        long size = file.getSize();
        //类型
        String type = FileUtil.extName(originalFilename);
        //创建父级目录
        File uploadParentFile=new File(studentPath);
        if (!(uploadParentFile.exists())){
            uploadParentFile.mkdir();
        }
        //防止重名 定义文件标识码
        String uuid= IdUtil.simpleUUID();
        File uploadFile=new File(studentPath+"/"+originalFilename);
        //获取文件MD5 校验是否重复文件
        String md5= SecureUtil.md5(file.getInputStream());
        //根据MD5去数据库校验是否存在
        String serviceMd5 = studentFileMapper.findMd5(md5);
        //判断文件是否存在
        if (serviceMd5==null){
            //把获取file存入系统磁盘
            file.transferTo(uploadFile);
            url= "http://"+serverIp+":8081/file/student/"+uuid+'.'+type;
            SysStudentFile studentFile=new SysStudentFile();
            studentFile.setName(originalFilename);
            studentFile.setType(type);
            studentFile.setSize(size/1024);
            studentFile.setUrl(url);
            studentFile.setMd5(md5);
            //插入
            studentFileMapper.saveFile(studentFile);
            //更新学生文件url

            sysUserService.updateFileURL(url,username);
        }
        else {
            url=studentFileMapper.url(md5);
        }

        return url;

    }
    //根据uuid下载文件
    @GetMapping("/{fileUUID}")
    public void downFile(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
       //根据文件
       File uploadFile=new File(filepath+"/"+fileUUID);
       ServletOutputStream os=response.getOutputStream();
       response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
       response.setContentType("application/octet-stream");
       //读取文件字节流
       os.write(FileUtil.readBytes(uploadFile));
       os.flush();
       os.close();
    }
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam(defaultValue = "") String filename){
        IPage<SysFile> page=new Page(pageNum,pageSize);
        QueryWrapper<SysFile> queryWrapper = new QueryWrapper<>();
        if (!(filename==null)){
            queryWrapper.like("name",filename);
        }
        try {
            /*fileService.page(page, queryWrapper);*/
            fileService.page(page,queryWrapper);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success(page);
    }
}
